package com.zqxq.auth.config;

import com.zqxq.auth.cache.UserFuncCache;
import com.zqxq.auth.filter.AuthFilter;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import java.util.HashMap;

/**
 * 过滤器注册
 */
@Data
@Component
public class WebFilterConfiguration {
    public static final int PHONE = 1;//手机号类型
    public static final int ID_NO = 2;//身份证类型
    public static final int BANK = 3;//银行卡类型

    @Autowired
    private AuthConfig authConfig;
    @Autowired
    private UserFuncCache userFuncCache;

    @Bean
    public Filter authFilter() {
        AuthFilter authFilter = new AuthFilter();
        authFilter.setUserFuncCache(userFuncCache);
        authFilter.setSkip_swagger(authConfig.getSkip_swagger());
        authFilter.setDataDesensitization(initDataDesensitization());
        return authFilter;
    }

    private HashMap<Integer, HashMap<String, Integer>> initDataDesensitization() {
        HashMap<Integer, HashMap<String, Integer>> map = new HashMap<>();
        if (!StringUtils.isEmpty(authConfig.getPhone_params())) {
            this.addParam(map, authConfig.getPhone_params(), PHONE);
        }
        if (!StringUtils.isEmpty(authConfig.getId_no_params())) {
            this.addParam(map, authConfig.getId_no_params(), ID_NO);
        }
        if (!StringUtils.isEmpty(authConfig.getBank_params())) {
            this.addParam(map, authConfig.getBank_params(), BANK);
        }
        return map;
    }

    private void addParam(HashMap<Integer, HashMap<String, Integer>> map, String str, int type) {
        HashMap<String, Integer> map1 = new HashMap<>();
        String[] strArr = str.split(",");
        for (String s : strArr) {
            map1.put(s, type);
        }
        map.put(type, map1);
    }

    @Bean
    public FilterRegistrationBean authFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(authFilter());
        registration.addUrlPatterns("/*");//拦截所有
        registration.setName("authFilter");
        registration.setOrder(1);
        return registration;
    }

}
